package threadSynchronization;

/**
 * @Author: WanqingLiu
 * @Date: 2023/02/02/15:03
 * 银行取钱问题
 */
public class Draw {
    public static void main(String[] args) {
        Account account = new Account("晚晴", 100);
        DrawThread wanqing = new DrawThread(account, 10);
        DrawThread xinyu = new DrawThread(account, 10);
        wanqing.start();
        xinyu.start();
    }
}

// 银行账户类
class Account {
    String name; // 账户名
    int nowNum; // 账户余额

    public Account(String name, int nowNum) {
        this.name = name;
        this.nowNum = nowNum;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getNowNum() {
        return nowNum;
    }

    public void setNowNum(int nowNum) {
        this.nowNum = nowNum;
    }
}

// 取钱线程
class DrawThread extends Thread {
    Account account; // 取钱的账户
    int drawNum; // 取走的钱
    public DrawThread(Account account, int drawNum){
        this.account = account;
        this.drawNum = drawNum;
    }
    @Override
    public void run() {
        // 锁住我们要操作的 account
        synchronized (account) {
            if ((account.getNowNum() - drawNum) < 0) {
                System.out.println("余额不足");
                return;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            account.setNowNum(account.getNowNum() - drawNum);
            System.out.println("当前余额为 ：" + account.getNowNum());
        }
    }
}
